import { exec } from "child_process";
import { Logger, ResultCmd } from "./Defines";
import { Environment } from "./Environment";
import { join, parse } from "path";

export class Handler {
    module = "Handler";

    /**@description 日志 */
    private _logger: Logger = null!;
    public get logger(): Logger {
        if (!this._logger) {
            this.logger = console;
        }
        return this._logger;
    }
    public set logger(value: Logger) {
        this._logger = value;
    }

    /**@description 保存bundles的名称 */
    readonly bundleName = Environment.bundleName;

    /**@description resources 目录名 */
    readonly resources = Environment.resources;

    /**@description 当前项目路径 */
    get projPath() {
        if (Environment.isCommand) {
            return join(__dirname, "../../../");
        } else {
            return join(__dirname, "../../../../../");
        }
    }

    /**@description bundles保存路径 */
    readonly bundlesPath = join(this.projPath, this.bundleName);

    /**@description 项目 assets 目录 */
    readonly assetsDBPath = join(this.projPath, "snack/assets");

    /**@description 项目 bundles 路径 */
    readonly assetsBundlesPath = join(this.projPath, `snack/assets/${this.bundleName}`);

    /**@description 项目 resources 路径 */
    readonly assetsResourcesPath = join(this.projPath, `snack/assets/${this.resources}`);

    /**@description 插件路径 */
    readonly extensionsPath = join(this.projPath, `snack/${Environment.extensionsName}`);

    /**@description 需要安装依赖的目录 */
    readonly extensions = Environment.extensions;

    /**@description 扩展插件配置保存路径 */
    readonly configPath = join(this.projPath, `snack/config`);

    /**@description 依赖库 */
    readonly node_modules = join(this.projPath, "tools/node_modules");

    /**@description 构建目录 */
    readonly buildPath = join(this.projPath, "snack/build");

    /**@description 当前插件路径 */
    get curExtensionPath() {
        return "";
    }

    /**@description 执行命令 */
    exec(cmd: string, isLog = true) {
        return new Promise<ResultCmd>((resolve, reject) => {
            isLog && this.logger.log(`执行命令 : ${cmd}`);
            let result = exec(cmd, (err, stdout, stderr) => {
                if (err) {
                    isLog && this.logger.error(`执行命令 : ${cmd}失败`);
                    isLog && this.logger.error(err);
                    resolve({ isSuccess: false, data: err });
                } else {
                    resolve({ isSuccess: true, data: stdout });
                }
            });
            result.stdout?.on("data", (data) => {
                isLog && this.logger.log(data)
            });
            result.stderr?.on("error", (data) => {
                isLog && this.logger.error(data);
            })
        })
    }

    chdir(path: string) {
        this.logger.log(`切换目录 : ${path}`);
        try {
            process.chdir(path);
        } catch (error) {
            this.logger.error(`切换目录 : ${path}失败`);
        }
        this.logger.log(`当前目录 : ${process.cwd()}`);
    }

    log(name: string, isEnd: boolean) {
        let start = "/****************** 【";
        let end = "】******************/"
        if (isEnd) {
            this.logger.log(`${start}${name} 完成 ${end}`)
        } else {
            this.logger.log(`${start}${name} 开始 ${end}`)
        }
    }
    
    /**@description 当前插件支持的Creator版本号 */
    get supportVersions() {
        return Environment.supportVersions;
    }

    /**
     * @description 是否支持
     * @param version 
     * @returns 
     */
    isSupport(version: string) {
        if (this.supportVersions.indexOf(version) >= 0) {
            return true;
        }
        return false;
    }

    isSupportUpdate(platform: string) {
        return Environment.isSupportUpdate(platform);
    }

    /**
     * @description 返回uuid
     * @param name 
     * @returns 
     */
    protected getUUID(name : string){
        let ret = parse(name);
        if ( Environment.build.md5Cache ){
            ret = parse(ret.name);
        }
        return ret.name;
    }

}